package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import com.sky.vo.UserReportVO;
import io.swagger.models.auth.In;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {

    String url = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 用户登录
     * @param dto
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginDTO dto) {


        //使用httpClient把微信的code发给微信官方，with appid和secret
        Map<String,String> map  =new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",dto.getCode());
        map.put("grant_type","authorization_code");

        //获取wechat官方返回的结果
        String result = HttpClientUtil.doGet(url,map);
        //接收结果进行验证，判定返回的openid是否有值。
        JSONObject jsonObject = JSON.parseObject(result);
        String openid = jsonObject.getString("openid");


        if(openid==null){
         throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //查询到user对象，就是老用户
        User user = userMapper.findByOpenId(openid);
        if(user==null){
         user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();
         userMapper.add(user);
        }

        // 设置BaseContext中的CurrentId
        BaseContext.setCurrentId(user.getId());
       // 组装VO
        Map<String, Object> claims =new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),claims);
        UserLoginVO vo = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        /*
         Map<String,Object> claims =  new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),claims);
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();

         */


        return vo;
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {

        //1、创建日期的集合
        List<LocalDate> dateList = new ArrayList<>();

        while(!begin.isAfter(end)){

            dateList.add(begin);
            begin = begin.plusDays(1);
        }

        //2、构建新用户的集合 和 总用户的集合

        List<Integer>  newUserList = new ArrayList<>();

        List<Integer> totalUserList = new ArrayList<>();

        //遍历日期集合，取出每一天的日期对象

        dateList.forEach(d->{
            //准备好一天的开始和结束时间
            LocalDateTime beginTime = LocalDateTime.of(d, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(d, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime",endTime);


            //查询user表得到新用户的数据
            Integer newUserCount = userMapper.userCount(map);
            newUserList.add(newUserCount);

            map.remove("beginTime");
            Integer totalUserCount = userMapper.userCount(map);
            totalUserList.add(totalUserCount);

        });

        //查询user表得到总用户的数据.

        //3、封装为vo返回

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }
}
